﻿using Dapper;

using MediatR;
using NPOI.SS.Formula.Functions;
using ProductIntory.Domains;
using ProductIntory.ErrorCodes;
using ProductIntory.Infrastructures.Implement;
using ProductIntory.Infrastructures.Interface;
using ProductIntory.Read.Apis.Application.Command.ProductsCommands;
using System.Text;

namespace ProductIntory.Read.Apis.Application.CommandHandler.ProductionCommandHandlers
{
    public class ShowProductsCommandHandler : IRequestHandler<ShowProductsCommand, ApiPaging<List<Products>>>
    {
        IBaseRepository<Products> Products;

        public ShowProductsCommandHandler(IBaseRepository<Products> Products)
        {
            this.Products = Products;

        }
        //测试
        public async Task<ApiPaging<List<Products>>> Handle(ShowProductsCommand request, CancellationToken cancellationToken)
        {
            var list = Products.GetAll();
            if (request.productname != null)
            {
                list = list.Where(c=>c.ProductName.Contains(request.productname));
            }
            if (request.productype != null)
            {
                list = list.Where(c=>c.ProductType==request.productype);
            }
            if (request.producState != null)
            {
                list = list.Where(c => c.ProductAttribute == request.producState);
            }


            var totalCount = list.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / request.pagesize);
            var data = list.OrderBy(x => x.Productions_Id).Skip((request.currentpage - 1) * request.pagesize).Take(request.pagesize).ToList();
            return new ApiPaging<List<Products>>
            {
                currentpage = request.currentpage,
                totalcount = totalCount,
                totalpages = totalPages,
                pagesize = request.pagesize,
                Code = ApiEnum.success,
                Message = "分页成功",
                Data = data
            };
        }
    }
}
